package org.lease.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.lease.common.exception.BizException;
import org.lease.common.result.Result;
import org.lease.common.result.ResultCode;

import javax.crypto.SecretKey;
import java.util.Date;

public class JWTUtil {
    private static final long tokenExpiration = 60 * 60 * 1000 * 24 * 7;
    private static final SecretKey secretKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());


    public static String createToken(Long userId, String username) {
        return Jwts.builder().setSubject("USER_INFO").setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).claim("userId", userId).claim("username", username).signWith(secretKey).compact();
    }

    public static Claims parseToken(String token) {

        if (token == null) {
            throw new BizException(ResultCode.ADMIN_LOGIN_AUTH);
        }

        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            throw new BizException(ResultCode.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new BizException(ResultCode.TOKEN_INVALID);
        }
    }
}